package com.atguigu.gmall.product.test.log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class LoggingProxy {
    private Object target;

    public LoggingProxy(Object object) {
        this.target = object;
    }

    public Object getProxy() {
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                System.out.println("Logging: The method " + methodName + "begins with " + Arrays.toString(args));
                Object result = method.invoke(target, args);
                System.out.println("Logging: The method " + methodName + " returns " + result);
                return result;
            }
        });
        return proxy;
    }
}